#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import unittest


class readTest(unittest.TestCase):
    '''
    手动封装try catch finally
    '''

    def test_readCommon(self):
        try:
            f = open('../.gitignore', 'r')
            print('try...except...finally', f.read())
        except IOError as e:
            print(e)
        finally:
            f.close()

    '''
    使用with，它已经替我们封装try...catch...finally 关闭流
    '''

    def test_Simple(self):
        with open('../.gitignore', 'r') as f:
            print('with:', f.read())

    '''
    read()表示读取全部：当读取大文件时，可能会爆内存，读小文件最方便
    '''

    def test_Read(self):
        with open('../.gitignore', 'r') as f:
            print('read():', f.read())

    '''
    read(size)表示每次读取size个字节：比较保险的写法
    '''

    def test_ReadSize(self):
        with open('../.gitignore', 'r') as f:
            print('read(size):', f.read(520))

    '''
    readLine()表示每次读一行
    '''

    def test_ReadLine(self):
        with open('../.gitignore', 'r') as f:
            print('readLine():', f.readline())

    '''
    readLines()表示一次性读取所有内容，并按行返回list
    '''

    def test_ReadLines(self):
        with open('../.gitignore', 'r') as f:
            print('readLines():', f.readlines())

    '''
    读取二进制文件，例如图片或视频等
    '''

    def test_ReadRB(self):
        with open('../.gitignore', 'rb') as f:
            print('read RB:', f.read())

    '''
    读取非UTF-8文件时，要指明要读取文件的编码
    '''

    def test_ReadRB(self):
        with open('../.gitignore', 'r', encoding='gbk') as f:
            print('read gbk', f.read())


if __name__ == '__main__':
    unittest.main()
